<template>
    <el-card v-loading="loading" class="patient_container">
        <template #header>
            <div class="card_header">
                <span>就诊人管理</span>
                <el-button @click="addUser" type="success" :icon="User">
                    {{ scene ? '添加就诊人' : '就诊人管理' }}
                </el-button>
            </div>
        </template>
        <!-- main 就诊人信息 -->
        <div v-if="scene" class="visitor">
            <Visitor @changeRemove="changeRemove" @changeScene="changeScene" :index="index" v-for="(item, index) in userArr"
                :user="item" :showDelete="true" class="visitor_item" :key="item.id" />
        </div>
        <div v-else class="patient_form">
            <el-divider content-position="left">就诊人信息</el-divider>
            <el-form ref="form1" :rules="rules1" :model="userParams" class="elForm" label-width="86">
                <el-form-item label="用户姓名" prop="name">
                    <el-input v-model="userParams.name" placeholder="请你输入用户姓名"></el-input>
                </el-form-item>
                <el-form-item label="证件类型" prop="certificatesType">
                    <el-select @change="changeCertificatesType" v-model="userParams.certificatesType"
                        placeholder="请你选择证件的类型">
                        <el-option v-for="item in certationArr" :key="item.id" :label="item.name" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="certificatesNo">
                    <el-input v-model="userParams.certificatesNo" placeholder="请你输入证件号码"></el-input>
                </el-form-item>
                <el-form-item label="用户性别" prop="sex">
                    <el-radio-group v-model="userParams.sex">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthdate">
                    <el-date-picker v-model="userParams.birthdate" value-format="YYYY-MM-DD" type="date"
                        placeholder="请你选择日期" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="userParams.phone" placeholder="请你输入手机号码"></el-input>
                </el-form-item>
            </el-form>
            <el-divider content-position="left">建档信息 <span>(完善后部分医院首次就诊不排队建档)</span></el-divider>
            <el-form ref="form2" :rules="rules2" :model="userParams" class="elForm" label-width="86">
                <el-form-item label="婚姻状况" prop="isMarry">
                    <el-radio-group v-model="userParams.isMarry">
                        <el-radio :label="1">已婚</el-radio>
                        <el-radio :label="0">未婚</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="自费/医保" prop="isInsure">
                    <el-radio-group v-model="userParams.isInsure">
                        <el-radio :label="1">自费</el-radio>
                        <el-radio :label="0">医保</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="当前的住址" prop="addressSelected">
                    <el-cascader v-model="userParams.addressSelected" :props="props" />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="userParams.address" placeholder="请你输入用户详细地址"></el-input>
                </el-form-item>
            </el-form>
            <el-divider content-position="left">联系人信息 (选填)</el-divider>
            <el-form ref="form3" :model="userParams" class="elForm" label-width="86">
                <el-form-item label="用户姓名" prop="contactsName">
                    <el-input v-model="userParams.contactsName" placeholder="请输入联系人姓名"></el-input>
                </el-form-item>
                <el-form-item label="证件类型" prop="contactsCertificatesType">
                    <el-select v-model="userParams.contactsCertificatesType" placeholder="请你选择证件的类型">
                        <el-option v-for="item in certationArr" :key="item.id" :label="item.name" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="contactsCertificatesNo">
                    <el-input v-model="userParams.contactsCertificatesNo" placeholder="请你输入证件号码"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="contactsPhone">
                    <el-input v-model="userParams.contactsPhone" placeholder="请你输入用户手机号码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="submit" type="primary" size="default">提交</el-button>
                    <el-button @click="reset" size="default">重写</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-card>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { User } from '@element-plus/icons-vue';
import Visitor from '@/components/visitor/index.vue'
import { reqGetUser } from '@/api/hospital';
import { reqCertationType, reqCity, reqAddOrUpdateUser } from '@/api/user';
import type { UserResponseData, UserArr } from '@/api/hospital/type';
import type { AddOrUpdateUser, CertationTypeResponseData, CertationArr } from '@/api/user/type';
// @ts-ignore
import type { CascaderProps } from 'element-plus';
// @ts-ignore
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
// @ts-ignore
import type { FormRules } from 'element-plus'
let $route = useRoute();
let $router = useRouter();
// 判断数据是否全部请求完毕
let loading = ref<boolean>(false);
// 存储全部就诊人信息
let userArr = ref<UserArr>([])
// 决定卡片身体部分的展示内容
let scene = ref<boolean>(true)
// 存储证件类型的数据
let certationArr = ref<CertationArr>([])
// 收集新增就诊人的数据
let userParams = reactive<AddOrUpdateUser>({
    name: "",
    certificatesType: "",
    certificatesNo: "",
    sex: 1,
    birthdate: "",
    phone: "",
    isMarry: 0,
    isInsure: 1,
    addressSelected: [],
    address: "",
    contactsName: "",
    contactsCertificatesType: "",
    contactsCertificatesNo: "",
    contactsPhone: "",
});
// 获取表单实例
let form1 = ref<any>();
let form2 = ref<any>();
let form3 = ref<any>();


// 自定义校验规则证件号码
const validatorCertificatesNo = (_: any, value: any, callBack: any) => {
    if (userParams.certificatesType === '20') {
        if (value.length == "9" && /\d{9}/.test(value)) {
            callBack();
        } else {
            callBack(new Error("请输入正确的九位户口本号码"));
        }
    } else if (userParams.certificatesType === '10') {
        if (value.length == "18" && /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
            callBack();
        } else {
            callBack(new Error("请输入正确的身份证"));
        }
    } else {
        callBack(new Error("请先选择证件的类型"));
    }
}
// 手机号验证规则
const validatePhone = (_: any, value: any, callback: any) => {
    if (!/^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"))
    } else {
        callback()
    }
}
// 验证具体的某个字段 校验certificatesNo字段
const changeCertificatesType = () => {
    form1.value.validateField('certificatesNo')
}
// 表单验证
const rules1 = reactive<FormRules>({
    name: [
        { required: true, message: '请输入就诊人姓名', trigger: 'blur' },
    ],
    certificatesType: [
        { required: true, message: '请选择就诊人证件类型', trigger: 'change' },
    ],
    certificatesNo: [
        { required: true, message: '请输入就诊人证件号码', trigger: 'blur' },
        { required: true, validator: validatorCertificatesNo }
    ],
    sex: [
        { required: true, message: '请选择就诊人性别', trigger: 'change' },
    ],
    birthdate: [
        { required: true, message: '请选择就诊人出生日期', trigger: 'change' },
    ],
    phone: [
        { required: true, message: '请输入就诊人手机号码', trigger: 'blur' },
        { required: true, validator: validatePhone }
    ],
})
const rules2 = reactive<FormRules>({
    isMarry: [
        { required: true, message: '请选择就诊人婚姻状况', trigger: 'change' },
    ],
    isInsure: [
        { required: true, message: '请选择自费/医保', trigger: 'change' },
    ],
    addressSelected: [
        { required: true, message: '请选择就诊人当前住址', trigger: 'change' },
    ],
    address: [
        { required: true, message: '请输入就诊人详细地址', trigger: 'blur' },
    ]
})

onMounted(() => {
    // 获取就诊人信息
    getAllUser();
    // 获取证件的类型
    getCertationType();
    //判断:当前这个路由组件是不是从挂号组件而来[挂号组件而来,路径上是携带query参数type=add]
    if ($route.query.type == "add" || $route.query.type == "edit") {
        scene.value = false;
    }
})

// 获取就诊人信息
const getAllUser = async () => {
    loading.value = await true
    let { code, data }: UserResponseData = await reqGetUser();
    if (code === 200) {
        userArr.value = data
    }
    loading.value = await false
}
// 添加就诊人按钮的回调
const addUser = () => {
    scene.value = !scene.value
    // 清空按钮
    reset();
}
// 子组件通知父组件修改就诊人信息
const changeScene = (user: AddOrUpdateUser) => {
    scene.value = false;
    Object.assign(userParams, user)
}
// 子组件通知父组件更新页面
const changeRemove = () => {
    getAllUser();
}
// 获取证件类型
const getCertationType = async () => {
    let { code, data }: CertationTypeResponseData = await reqCertationType()
    if (code === 200) {
        certationArr.value = data
    }
}
// 级联选择器数据
const props: CascaderProps = {
    lazy: true,
    async lazyLoad(node: any, resolve: any) {
        let result = await reqCity(node.data.id || '86')
        // 整理数据
        let showData = result.data.map((item: any) => {
            return {
                id: item.id,
                label: item.name,
                value: item.value,
                leaf: !item.hasChildren
            }
        });
        // 注入组件需要展示的数据
        resolve(showData)
    }
}
// 提交按钮方法的回调
const submit = async () => {
    let flag1: boolean = false;
    let flag2: boolean = false;
    loading.value = await true
    await form1.value.validate((valid: any) => {
        if (valid) {
            flag1 = true
        }
    })
    await form2.value.validate((valid: any) => {
        if (valid) {
            flag2 = true
        }
    })
    if (flag1 && flag2) {
        // 要么新增就诊人 || 更新就诊人
        let { code } = await reqAddOrUpdateUser(userParams)
        if (code === 200) {
            await getAllUser();
            // 提交按钮的时候判断是不是从预约挂号而来
            if ($route.query.type) {
                await $router.back()
            } else {
                scene.value = await true;
            }
            await ElMessage({
                type: 'success',
                message: userParams.id ? '更新成功' : '添加成功'
            });
        } else {
            ElMessage({
                type: 'error',
                message: userParams.id ? '更新失败' : '添加失败'
            })
        }
    }
    loading.value = await false
}
// 清空按钮
const reset = () => {
    form1.value?.resetFields()
    form2.value?.resetFields()
    form3.value?.resetFields()
    Object.assign(userParams, {
        id: '',
        name: "",
        certificatesType: "",
        certificatesNo: "",
        sex: 1,
        birthdate: "",
        phone: "",
        isMarry: 0,
        isInsure: 1,
        addressSelected: [],
        address: "",
        contactsName: "",
        contactsCertificatesType: "",
        contactsCertificatesNo: "",
        contactsPhone: "",
    })
}
// 监听全部就诊人的数据
watch(() => userArr.value, () => {
    if ($route.query.type == "edit") {
        let user = userArr.value.find((item: any) => {
            return item.id == $route.query.id;
        });
        Object.assign(userParams, user)
    }
});
</script>
<style scoped lang="scss">
.patient_container {
    .card_header {
        font-size: 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .visitor {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        .visitor_item {
            width: 32%;
            margin-bottom: 16px;
        }
    }

    .patient_form {
        .elForm {
            width: 60%;
            margin: 0 auto;
        }

        :deep(.el-divider) {
            .el-divider__text {
                color: lightpink;
            }
        }
    }
}

@media (max-width:1280px) {
    .patient_container {
        .visitor {
            justify-content: space-around;

            .visitor_item {
                width: 46%;
            }
        }
    }
}

@media (max-width:768px) {
    .patient_container {
        .card_header {
            flex-direction: column;
            font-size: 18px;

            span {
                align-self: self-start;
                margin-bottom: 10px;
            }

            :deep(.el-button) {
                align-self: self-end;
                font-size: 12px;
            }
        }

        .visitor {
            justify-content: center;

            .visitor_item {
                width: 100%;
            }
        }

        .patient_form {
            .elForm {
                width: 100%;

                :deep(.el-form-item__label) {
                    font-size: 12px;
                }

                :deep(.el-button) {
                    font-size: 12px;
                    width: 44px;
                    height: 28px;
                }

                :deep(.el-radio:nth-child(1)) {
                    margin-right: 10px;
                }
            }

            :deep(.el-divider) {
                .el-divider__text {

                    span {
                        display: none;
                    }
                }
            }
        }
    }
}
</style>